package com.ruoyi.framework.config;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;

// 自定义Redis序列化器（添加命名空间前缀）
public class NamespaceStringRedisSerializer implements RedisSerializer<String> {
    private final String namespace;
    private final StringRedisSerializer defaultSerializer = new StringRedisSerializer();

    public NamespaceStringRedisSerializer(String namespace) {
        this.namespace = namespace;
    }

    @Override
    public byte[] serialize(String string) throws SerializationException {
        String keyWithNamespace = namespace + ":" + string;
        return defaultSerializer.serialize(keyWithNamespace);
    }

    @Override
    public String deserialize(byte[] bytes) throws SerializationException {
        String originalKey = defaultSerializer.deserialize(bytes);
        return originalKey != null ? originalKey.replaceFirst(namespace + ":", "") : null;
    }
}
